// Fried衰弱评估逻辑配置文件
export const assessmentLogic = {
  // 诊断标准配置
  diagnosisRules: {
    frail: {
      minScore: 3,
      maxScore: 5,
      label: '衰弱综合征'
    },
    prefrail: {
      minScore: 1,
      maxScore: 2,
      label: '衰弱前期'
    },
    healthy: {
      minScore: 0,
      maxScore: 0,
      label: '无衰弱健康老人'
    }
  },

  // 各项评估的计算规则
  assessmentRules: {
    // 1. 体重下降评估
    weightLoss: {
      name: '体重下降',
      calculate: (formData) => {
        const positive = formData.weightLoss === 'yes';
        return {
          positive,
          score: positive ? 1 : 0,
          result: positive ? '是' : '否'
        };
      }
    },

    // 2. 行走时间评估
    walkTime: {
      name: '行走时间',
      calculate: (formData) => {
        let positive = false;
        const { gender, height, walkTime } = formData;
        
        if (gender === 'male') {
          positive = (height <= 173 && walkTime >= 7) || (height > 173 && walkTime >= 6);
        } else {
          positive = (height <= 159 && walkTime >= 7) || (height > 159 && walkTime >= 6);
        }
        
        return {
          positive,
          score: positive ? 1 : 0,
          result: `${walkTime}秒`
        };
      }
    },

    // 3. 握力评估
    gripStrength: {
      name: '握力',
      calculate: (formData) => {
        let positive = false;
        const { gender, weight, height, gripStrength } = formData;
        const bmi = weight / Math.pow(height / 100, 2);
        
        if (gender === 'male') {
          if (bmi <= 24.0) {
            positive = gripStrength <= 29;
          } else if (bmi <= 26.0) {
            positive = gripStrength <= 30;
          } else if (bmi <= 28.0) {
            positive = gripStrength <= 30;
          } else {
            positive = gripStrength <= 32;
          }
        } else {
          if (bmi <= 23.0) {
            positive = gripStrength <= 17;
          } else if (bmi <= 26.0) {
            positive = gripStrength <= 17.3;
          } else if (bmi <= 29.0) {
            positive = gripStrength <= 18;
          } else {
            positive = gripStrength <= 21;
          }
        }
        
        return {
          positive,
          score: positive ? 1 : 0,
          result: `${gripStrength}kg (BMI: ${bmi.toFixed(1)})`
        };
      }
    },

    // 4. 体力活动评估
    physicalActivity: {
      name: '体力活动',
      calculate: (formData) => {
        const { gender, physicalActivity } = formData;
        const threshold = gender === 'male' ? 383 : 270;
        const positive = physicalActivity < threshold;
        
        return {
          positive,
          score: positive ? 1 : 0,
          result: `${physicalActivity}kcal/周`
        };
      }
    },

    // 5. 疲乏评估
    fatigue: {
      name: '疲乏',
      calculate: (formData) => {
        const { fatigue1, fatigue2 } = formData;
        const score1 = parseInt(fatigue1);
        const score2 = parseInt(fatigue2);
        const positive = score1 >= 2 || score2 >= 2;
        
        return {
          positive,
          score: positive ? 1 : 0,
          result: `问题1: ${score1}分, 问题2: ${score2}分`
        };
      }
    }
  },

  // 统计分析规则
  statisticsRules: {
    // 计算各项目阳性率
    calculateItemRates: (surveys) => {
      const total = surveys.length;
      if (total === 0) return {};

      let weightLoss = 0, walkTimeAbnormal = 0, gripStrengthLow = 0, activityLow = 0, fatigue = 0;

      surveys.forEach(survey => {
        // 体重下降
        if (survey.weightLoss === 'yes') weightLoss++;

        // 行走时间异常判断
        let walkTimeAbnormal_flag = false;
        if (survey.gender === 'male') {
          walkTimeAbnormal_flag = (survey.height <= 173 && survey.walkTime >= 7) || (survey.height > 173 && survey.walkTime >= 6);
        } else {
          walkTimeAbnormal_flag = (survey.height <= 159 && survey.walkTime >= 7) || (survey.height > 159 && survey.walkTime >= 6);
        }
        if (walkTimeAbnormal_flag) walkTimeAbnormal++;

        // 握力不足判断
        const bmi = survey.weight / Math.pow(survey.height / 100, 2);
        let gripStrengthLow_flag = false;
        if (survey.gender === 'male') {
          if (bmi <= 24.0) gripStrengthLow_flag = survey.gripStrength <= 29;
          else if (bmi <= 26.0) gripStrengthLow_flag = survey.gripStrength <= 30;
          else if (bmi <= 28.0) gripStrengthLow_flag = survey.gripStrength <= 30;
          else gripStrengthLow_flag = survey.gripStrength <= 32;
        } else {
          if (bmi <= 23.0) gripStrengthLow_flag = survey.gripStrength <= 17;
          else if (bmi <= 26.0) gripStrengthLow_flag = survey.gripStrength <= 17.3;
          else if (bmi <= 29.0) gripStrengthLow_flag = survey.gripStrength <= 18;
          else gripStrengthLow_flag = survey.gripStrength <= 21;
        }
        if (gripStrengthLow_flag) gripStrengthLow++;

        // 体力活动不足
        const activityThreshold = survey.gender === 'male' ? 383 : 270;
        if (survey.physicalActivity < activityThreshold) activityLow++;

        // 疲乏
        if (parseInt(survey.fatigue1) >= 2 || parseInt(survey.fatigue2) >= 2) fatigue++;
      });

      return {
        weightLossRate: ((weightLoss / total) * 100).toFixed(1),
        walkTimeRate: ((walkTimeAbnormal / total) * 100).toFixed(1),
        gripStrengthRate: ((gripStrengthLow / total) * 100).toFixed(1),
        activityRate: ((activityLow / total) * 100).toFixed(1),
        fatigueRate: ((fatigue / total) * 100).toFixed(1)
      };
    },

    // 计算诊断分布
    calculateDiagnosisDistribution: (surveys) => {
      const total = surveys.length;
      if (total === 0) return {};

      let frail = 0, prefrail = 0, healthy = 0;
      
      surveys.forEach(survey => {
        if (survey.diagnosis === '衰弱综合征') frail++;
        else if (survey.diagnosis === '衰弱前期') prefrail++;
        else healthy++;
      });

      return {
        frail,
        prefrail,
        healthy,
        frailPercent: ((frail / total) * 100).toFixed(1),
        prefrailPercent: ((prefrail / total) * 100).toFixed(1),
        healthyPercent: ((healthy / total) * 100).toFixed(1)
      };
    },

    // 计算基本统计信息
    calculateBasicStats: (surveys) => {
      const total = surveys.length;
      if (total === 0) return {};

      let totalAge = 0, totalBMI = 0;
      let maleCount = 0, femaleCount = 0;

      surveys.forEach(survey => {
        totalAge += survey.age;
        const bmi = survey.weight / Math.pow(survey.height / 100, 2);
        totalBMI += bmi;

        if (survey.gender === 'male') maleCount++;
        else femaleCount++;
      });

      return {
        avgAge: totalAge / total,
        avgBMI: totalBMI / total,
        maleCount,
        femaleCount
      };
    }
  },

  // 报告生成规则
  reportTemplates: {
    // 个人报告模板
    individualReport: (survey, recorderInfo) => {
      const bmi = survey.weight / Math.pow(survey.height / 100, 2);
      return `Fried衰弱评估个人报告
问答编号：${survey.surveyId}
评估时间：${survey.recordTime}

=== 记录人信息 ===
记录人：${recorderInfo.name}
职务：${recorderInfo.position}
机构：${recorderInfo.institution || '未填写'}

=== 被评估人信息 ===
姓名：${survey.patientName}
年龄：${survey.age}岁
性别：${survey.gender === 'male' ? '男性' : '女性'}
身高：${survey.height}cm
体重：${survey.weight}kg
BMI：${bmi.toFixed(1)}
联系电话：${survey.phone || '未填写'}

=== 评估结果 ===
总分：${survey.totalScore}/5
诊断：${survey.diagnosis}

=== 原始数据 ===
体重下降：${survey.weightLoss === 'yes' ? '是' : '否'}
行走时间：${survey.walkTime}秒
握力：${survey.gripStrength}kg
体力活动：${survey.physicalActivity}kcal/周
疲乏评分1：${survey.fatigue1}分
疲乏评分2：${survey.fatigue2}分

备注：${survey.remarks || '无'}
`;
    },

    // 汇总报告模板
    summaryReport: (surveys, recorderInfo, statistics) => {
      const timestamp = new Date().toLocaleString('zh-CN');
      const surveyId = recorderInfo.surveyId;

      return `Fried衰弱评估数据汇总报告
问答编号：${surveyId}
导出时间：${timestamp}
记录人：${recorderInfo.name}
所属机构：${recorderInfo.institution || '未填写'}
问卷总数：${surveys.length}份

=== 统计分析 ===

衰弱综合征：${statistics.frail}份 (${statistics.frailPercent}%)
衰弱前期：${statistics.prefrail}份 (${statistics.prefrailPercent}%)
无衰弱健康老人：${statistics.healthy}份 (${statistics.healthyPercent}%)

平均年龄：${statistics.avgAge.toFixed(1)}岁
男性：${statistics.maleCount}份，女性：${statistics.femaleCount}份
平均BMI：${statistics.avgBMI.toFixed(1)}

各项目阳性率：
- 体重下降：${statistics.weightLossRate}%
- 行走时间异常：${statistics.walkTimeRate}%
- 握力不足：${statistics.gripStrengthRate}%
- 体力活动不足：${statistics.activityRate}%
- 疲乏：${statistics.fatigueRate}%
`;
    },

    // 详细数据CSV模板
    detailsCSV: (surveys) => {
      let content = `问答编号,记录时间,被评估人姓名,年龄,性别,身高(cm),体重(kg),BMI,体重下降,行走时间(秒),握力(kg),体力活动(kcal/周),疲乏1,疲乏2,总分,诊断结果,备注\n`;

      surveys.forEach(survey => {
        const bmi = survey.weight / Math.pow(survey.height / 100, 2);
        content += `${survey.surveyId},${survey.recordTime},${survey.patientName},${survey.age},${survey.gender === 'male' ? '男' : '女'},${survey.height},${survey.weight},${bmi.toFixed(1)},${survey.weightLoss === 'yes' ? '是' : '否'},${survey.walkTime},${survey.gripStrength},${survey.physicalActivity},${survey.fatigue1},${survey.fatigue2},${survey.totalScore},${survey.diagnosis},${survey.remarks || ''}\n`;
      });

      return content;
    },

    // 评估结果报告模板
    assessmentReport: (formData, recorderInfo, result, bmi) => {
      const timestamp = new Date().toLocaleString('zh-CN');
      const recordTime = formData.recordTime ?
        new Date(formData.recordTime).toLocaleString('zh-CN') :
        timestamp;

      return `Fried衰弱评估结果报告
问答编号：${recorderInfo.surveyId}
生成时间：${timestamp}

=== 记录人信息 ===
记录人姓名：${recorderInfo.name}
记录人职务/身份：${recorderInfo.position}
所属机构：${recorderInfo.institution}
联系方式：${recorderInfo.contact}
记录时间：${recordTime}
备注：${formData.remarks || '无'}

=== 被评估人基本信息 ===
姓名：${formData.patientName}
年龄：${formData.age}岁
性别：${formData.gender === 'male' ? '男性' : '女性'}
身高：${formData.height}cm
体重：${formData.weight}kg
BMI：${bmi.toFixed(1)}
联系电话：${formData.phone || '未填写'}

=== 评估结果 ===
总分：${result.totalScore}/5
诊断结果：${result.diagnosis}

=== 各项详细结果 ===
${result.details.map((item, index) =>
        `${index + 1}. ${item.name}：${item.result} ${item.positive ? '(阳性)' : '(阴性)'}`
      ).join('\n')}

=== 评分标准 ===
• 具备5条中3条及以上：衰弱综合征
• 不足3条：衰弱前期  
• 0条：无衰弱健康老人

=== 原始评估数据 ===
体重下降：${formData.weightLoss === 'yes' ? '是' : '否'}
行走时间：${formData.walkTime}秒
握力：${formData.gripStrength}kg
体力活动：${formData.physicalActivity}kcal/周
疲乏评分1：${formData.fatigue1}分
疲乏评分2：${formData.fatigue2}分

报告结束
`;
    }
  }
};

// 主要的评估计算函数
export const calculateAssessment = (formData) => {
  let totalScore = 0;
  const details = [];
  const rules = assessmentLogic.assessmentRules;

  // 按顺序计算各项评估
  const assessmentOrder = ['weightLoss', 'walkTime', 'gripStrength', 'physicalActivity', 'fatigue'];
  
  assessmentOrder.forEach(key => {
    if (rules[key]) {
      const result = rules[key].calculate(formData);
      totalScore += result.score;
      details.push({
        name: result.name || rules[key].name,
        result: result.result,
        positive: result.positive
      });
    }
  });

  // 确定诊断结果
  let diagnosis = '';
  const diagnosisRules = assessmentLogic.diagnosisRules;
  
  if (totalScore >= diagnosisRules.frail.minScore) {
    diagnosis = diagnosisRules.frail.label;
  } else if (totalScore >= diagnosisRules.prefrail.minScore) {
    diagnosis = diagnosisRules.prefrail.label;
  } else {
    diagnosis = diagnosisRules.healthy.label;
  }

  return {
    totalScore,
    diagnosis,
    details
  };
};

// 统计分析函数
export const calculateStatistics = (surveys) => {
  const rules = assessmentLogic.statisticsRules;
  
  const itemRates = rules.calculateItemRates(surveys);
  const diagnosisDistribution = rules.calculateDiagnosisDistribution(surveys);
  const basicStats = rules.calculateBasicStats(surveys);

  return {
    ...itemRates,
    ...diagnosisDistribution,
    ...basicStats
  };
};